<template>
  <div class="container">
    <div class="app-container">
      <!-- 树形结构
       data提供数据
       props提供属性配置
       default-expand-all是否默认展开节点 -->
      <el-tree :data="depts" default-expand-all :props="defaultProps" :expand-on-click-node="false">
        <template v-slot="{data}">
          <el-row style="width:100%;" type="flex" justify="space-between" align="middle">
            <el-col>
              {{ data.name }}
            </el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <el-dropdown @command="operateDept($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>

                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>

                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>

                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown></el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 添加部门 -->
    <addDept ref="addDept" :current-node-id="currentNodeId" :show-dialog.sync="showDialog" @updateDepartment="getDepartment" />
  </div>
</template>
<script>
import addDept from './components/add-dept.vue'
import { delDepartment, getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Department',
  managerName: '管理员',
  components: {
    addDept
  },
  data() {
    return {
      depts: [],
      currentNodeId: null, // 存储当前点击的id
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartment()
      this.depts = transListToTreeData(res, 0)
      console.log(res)
    },
    operateDept(type, id) {
      console.log('你操作的行为', type, id)
      if (type === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      } else if (type === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
        // 更新props- 异步动作
        // 直接调用了子组件的方法是同步的方法
        // 要在子组件获取数据
        // 父组件调用子组件的方法来获取数据
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      } else {
        this.$confirm('您确认要删除该部门吗').then(async() => {
          await delDepartment(id)
          this.$message.success('删除部门成功')
          this.getDepartment()
        })
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 40px;
  font-size: 14px;
}
.tree-manager {
  width: 80px;
  display: inline-block;
  margin: 10px;
}
</style>
